const MYSQL = require("../../sql/mysql");
const userSQLName = "feedback";
const Config = require("../../config");
const Redis = require("../../sql/redis");
let RedisConfig = Config.Radis;
let ProjectName = RedisConfig.project;
// 用户设备表
const deviceSqlName = "user_device";
/**
 * 查看用户基础信息
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function GetUserBaseInfo(Request) {
  try {
    let RequestTypeof = typeof Request;
    let user = null;
    if (RequestTypeof == "object") {
      if (Request?.query?.user) {
        let query = Request.query;
        user = query.user;
      }
    } else {
      user = Request;
    }
    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }
    let RedisPath = `${ProjectName}:user:${user}:BaseInfo`;
    let userInfo = null;
    const RedisUserBaseInfoExists = await Redis.hexists(RedisPath, "id");
    if (RedisUserBaseInfoExists) {
      userInfo = await Redis.hgetall(RedisPath);
    } else {
      const Conline = await MYSQL.promise().getConnection();
      let StartMysqlQuery = await Conline.query(
        `SELECT * FROM users WHERE id = ${user}`
      );
      // 查询完毕，释放池连接回池
      await Conline.release();
      // 取出数据
      let userList = StartMysqlQuery[0];
      userInfo = userList[0];
    }
    let {
      id,
      apply,
      type,
      is_user_temporary,
      user_temporary_expire_time,
      activation_state,
      activation_method,
      activation_time,
      inviter,
      division_id,
      position_id,
      info_background_image,
      avatar,
      roles,
      introduce,
      grouping,
      nickname,
      username,
      real_state,
      last_login_type,
      last_login_agent,
      last_login_device,
      last_login_ip,
      last_login_time,
      last_login_date,
      last_login_secretKey,
      last_login_secretKey_expired_date,
      register_method,
      register_type,
      register_device,
      register_ip,
      register_time,
      register_date,
      birth_year,
      birth_month,
      birth_day,
      super_admin,
      gender,
      mobile,
      wechat,
      qq,
      email,
      postcode,
      logoff_end_dete,
      lock,
      lock_start_date,
      lock_end_date,
      is_black_user,
      custom_setting,
      comment,
      state,
    } = userInfo;
    await Redis.hset(RedisPath, userInfo);
    return {
      code: 0,
      msg: "操作成功",
      data: {
        id,
        apply,
        type,
        is_user_temporary,
        user_temporary_expire_time,
        activation_state,
        activation_method,
        activation_time,
        inviter,
        division_id,
        position_id,
        info_background_image,
        avatar,
        roles,
        introduce,
        grouping,
        nickname,
        username,
        real_state,
        last_login_type,
        last_login_agent,
        last_login_device,
        last_login_ip,
        last_login_time,
        last_login_date,
        last_login_secretKey,
        last_login_secretKey_expired_date,
        register_method,
        register_type,
        register_device,
        register_ip,
        register_time,
        register_date,
        birth_year,
        birth_month,
        birth_day,
        super_admin,
        gender,
        mobile,
        wechat,
        qq,
        email,
        postcode,
        logoff_end_dete,
        lock,
        lock_start_date,
        lock_end_date,
        is_black_user,
        custom_setting,
        comment,
        state,
      },
    };
  } catch (error) {
    console.log(error);
    return error;
  }
}

/**
 * 查看用户认证信息
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function GetUserRealInfo(Request) {
  try {
    let query = Request.query;

    let { user } = query;

    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }
    let userInfo = null;
    const Connection = await MYSQL.promise().getConnection();
    let StartMysqlQuery = await Connection.query(
      `
            SELECT * FROM users WHERE id = ${user}
        `
    );
    // 取出数据
    let userList = StartMysqlQuery[0];
    // 查询完毕，释放池连接回池
    await Connection.release();
    if (userList.length) {
      userInfo = userList[0];
    } else {
      userInfo = {};
    }
    return {
      code: 0,
      msg: "操作成功",
      data: userInfo ?? {},
    };
  } catch (error) {
    console.log(error);
    return error;
  }
}

/**
 * 修改用户信息
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function UpdateUserBaseInfo(Request) {
  try {
    let Body = Request.body;
    let { user, update } = Body.user;
    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }
    delete update.id;
    const MysqlClient = await MYSQL.promise().getConnection();
    // 开始事务
    await MysqlClient.beginTransaction();
    // 更新数据
    let updateResult = await MysqlClient.query(
      `
            update users set ? where id = ${user}
        `,
      update
    );
    // 取出更新结果
    let affectedRows = updateResult[0].affectedRows;
    if (affectedRows) {
      // 提交事务
      await connection.commit();
      // 查询完毕，释放池连接回池
      await connection.release();
      return {
        code: 0,
        msg: "更新成功",
      };
    } else {
      // 回滚事务
      await connection.rollback();
      // 查询完毕，释放池连接回池
      await connection.release();
      // 返回结果
      throw {
        code: 500,
        msg: "修改失败,未修改任何信息",
      };
    }
  } catch (error) {
    throw error;
  }
}

/**
 * 修改用户认证信息
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function UpdateUserRealInfo(Request) {}
/**
 * 重置用户密码
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function ResetUserPassword(Request) {
  try {
    let Body = Request.body;
    let { user, password } = Body;
    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }
    if (!password) {
      throw { code: 500, msg: "密码不能为空" };
    }
    const MysqlClient = await MYSQL.promise().getConnection();
  } catch (error) {}
}

/**
 * 删除用户
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteUser(Request) {
  try {
    let Body = Request.body;

    let { user } = Body;

    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }

    const MysqlClient = await MYSQL.promise().getConnection();
    // 开始事务
    await MysqlClient.beginTransaction();
    //

    // 更新数据
    let updateResult = await MysqlClient.query(
      `
                update users set state = 0 where id = ${user}
            `
    );

    // 取出更新结果
    let affectedRows = updateResult[0].affectedRows;

    if (affectedRows) {
      // 提交事务
      await connection.commit();
      // 查询完毕，释放池连接回池
      await connection.release();
      return {
        code: 0,
        msg: "删除成功",
      };
    } else {
      // 回滚事务
      await connection.rollback();
      // 查询完毕，释放池连接回池
      await connection.release();
      // 返回结果
      throw {
        code: 500,
        msg: "删除失败,未知错误",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 认证管理列表
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function UserRealList(params = {}) {
  try {
    let { page = 1, limit = 10 } = params;
    let query = `
          SELECT * FROM users 
          WHERE real_state = 1
          LIMIT  ${limit} OFFSET ${(page - 1) * limit};
      `;
    const connection = await MYSQL.promise().getConnection();
    let [rows, fields] = await connection.query(query);
    let pages = Math.ceil(rows.length / limit);
    // 查询完毕，释放池连接回池
    await connection.release();
    return {
      code: 0,
      msg: "获取认证列表成功",
      data: {
        page,
        pages,
        limit,
        list: rows,
        total: rows.length,
      },
    };
  } catch (error) {
    console.log(error);
    return {
      code: 500,
      msg: "操作失败,数据库操作出现错误",
    };
  }
}
/**
 * 通过认证
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function PassReal(Request) {}

/**
 * 拒绝认证
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function RefuseReal(Request) {
  try {
    let Body = Request.body;

    let { id, user_id, reviewer_id, remarks } = Body;

    let updateQuery = `
          UPDATE ${SQLName} SET ?
          WHERE id = ${id}
      `;
  } catch (error) {
    console.log(error);
    return {
      code: 500,
      msg: "操作失败,数据库操作出现错误",
    };
  }
}
/**
 * 禁止用户认证
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function ProhibitReal(Request) {
  try {
    let Body = Request.body;
    let { user } = Body;
    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // 开始更新MYSQL
    let updateUserInfo = await Conline.query(
      `UPDATE users SET ? WHERE id = ${user}`,
      {
        real_prohibit: 1,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    let affectedRows = updateUserInfo[0].affectedRows;
    if (affectedRows) {
      return {
        code: 0,
        msg: "操作成功",
      };
    } else {
      throw {
        code: 500,
        msg: "操作失败,未知错误",
      };
    }
  } catch (error) {
    console.log(error);
    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 恢复用户认证资格
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function CancelProhibitReal(Request) {
  try {
    let Body = Request.body;
    let { user } = Body;
    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // 开始更新MYSQL
    let updateUserInfo = await Conline.query(
      `UPDATE users SET ? WHERE id = ${user}`,
      {
        real_prohibit: 0,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    let affectedRows = updateUserInfo[0].affectedRows;
    if (affectedRows) {
      return {
        code: 0,
        msg: "操作成功",
      };
    } else {
      throw {
        code: 500,
        msg: "操作失败,未知错误",
      };
    }
  } catch (error) {
    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 重置用户已认证信息
 * @param {*} params
 * @param {*} params.user 用户
 */
async function ResetReal(Request) {
  try {
    let query = Request.query;
    let { user } = query;
    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }
    let updateQuery = `
          UPDATE ${SQLName} SET ?
          WHERE id = ${user}
        `;
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // 更新用户信息
    await Conline.query(updateQuery, {
      real_type: null,
      real_info: null,
      real_state: null,
      real_result: null,
      real_create_date: null,
      real_pass_date: null,
      real_pass_reason: null,
      real_error_date: null,
      real_error_reason: null,
    });
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "重置成功",
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 获取用户列表
 * @param {*} params
 * @param {*} params.page
 */
async function userList(Request) {
  try {
    let query = Request.query;

    let {
      page = 1, // 当前页
      limit = 10, // 每页记录数量
    } = query;
    limit = limit < 10 ? (limit = 1) : limit;
    page = page < 1 ? (page = 1) : page;

    let SqlQuery = `
        SELECT  *
        FROM users
        LIMIT  ${limit} OFFSET ${(page - 1) * limit};
        `;

    // 获取Mysql池链接
    const Connection = await MYSQL.promise().getConnection();

    let StartMysql = await Connection.query(SqlQuery);

    // 取出用户数据列表
    let list = StartMysql[0];

    // 获取数据总数 =====
    let totalResult = await Connection.query(
      `
        SELECT Count(*) AS total FROM users
        `
    );
    // 查询完毕，释放池连接回池
    await Connection.release();
    // 取出数据总数
    let total = totalResult[0][0].total;
    // 根据数据总数计算总页数
    let pages = Math.ceil(total / limit);
    list = list.map((userInfo) => {
      delete userInfo.password;
      return userInfo;
    });

    return {
      code: 0,
      msg: "获取成功",
      data: {
        pages,
        list,
        page: Number(page),
        limit: Number(limit),
        total: Number(total),
      },
    };
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "获取失败" };
  }
}
/**
 * 获取黑名单用户列表
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function Blacklist(Request) {
  try {
    let query = Request.query;

    let {
      page = 1, // 当前页
      limit = 10, // 每页记录数量
    } = query;
    limit = limit < 1 ? (limit = 1) : limit;
    page = page < 1 ? (page = 1) : page;
    // 黑名单状态码
    let BlacklistStateCode = 0;
    let listquery = `
            SELECT * FROM users WHERE 
            state = ${BlacklistStateCode}
            LIMIT  ${limit} OFFSET ${(page - 1) * limit};
        `;
    const Connection = await MYSQL.promise().getConnection();
    // 获取列表数据
    let mysqlResult = await Connection.query(listquery);
    list = mysqlResult[0];
    // 获取数据总数 =====
    let totalResult = await Connection.query(
      `
        SELECT Count(*) AS total FROM users WHERE state = ${BlacklistStateCode}
      `
    );
    // 查询完毕，释放池连接回池
    await Connection.release();
    total = totalResult[0][0].total;
    // 根据数据总数计算总页数
    let pages = Math.ceil(total / limit);
    return {
      code: 0,
      msg: "获取成功",
      data: {
        page,
        limit,
        list,
        total,
        pages,
      },
    };
  } catch (error) {
    console.log(error);
    throw {
      code: 500,
      msg: "操作失败,在获取黑名单列表发生错误",
    };
  }
}
/**
 * 取消拉黑
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function CancelBlack(Request) {
  try {
    let Body = Request.body;
    let { user } = Body;

    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // 开始更新MYSQL
    let updateUserInfo = await Conline.query(
      `UPDATE users SET ? WHERE id = ${user}`,
      {
        state: 1,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    let affectedRows = updateUserInfo[0].affectedRows;
    if (affectedRows) {
      return {
        code: 0,
        msg: "移除拉黑成功",
      };
    } else {
      throw {
        code: 500,
        msg: "移除失败,未知错误",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 拉黑用户
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function ToBlack(Request) {
  try {
    let Body = Request.body;
    let { user } = Body;
    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }
    // 查询用户信息,是否为超级管理员
    let { data: userInfo } = await GetUserBaseInfo(user);
    let { super_admin } = userInfo;
    if (super_admin) {
      throw { code: 500, msg: "操作失败,不允许拉黑超级管理员" };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // 开始更新MYSQL
    let updateUserInfo = await Conline.query(
      `UPDATE users SET ? WHERE id = ${user}`,
      {
        state: 0,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    let affectedRows = updateUserInfo[0].affectedRows;
    if (affectedRows) {
      return {
        code: 0,
        msg: "拉黑成功",
      };
    } else {
      throw {
        code: 500,
        msg: "拉黑失败,未知错误",
      };
    }
  } catch (error) {
    throw error;
  }
}

/**
 * 设置超级管理员
 * @param {object} params 配置对象
 * @param {object} params.user 用户
 * @param {object} params.super_admin 超级管理员
 * @return {promise<{code:string,msg:string}>}
 */
async function SetSuperUser(Request) {
  try {
    let Query = Request.query;

    let { user, super_admin } = Query;

    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    } else if (super_admin == null || super_admin == undefined) {
      throw { code: 500, msg: "super_admin不能为空" };
    }

    super_admin = Boolean(Number(super_admin));

    if (!super_admin) {
      let GetSuperNumber = await superNumberModule();
      let SuperNumber = GetSuperNumber.data;
      if (SuperNumber <= 1) {
        throw { code: 500, msg: "操作失败,至少保持一名超级管理员" };
      }
    }

    let updateQuery = `
              UPDATE ${SQLName} SET ?
              WHERE id = ${user}
           `;
    // 更新用户信息
    await MYSQL.promise().query(updateQuery, {
      super_admin: Number(super_admin),
    });
    return {
      code: 0,
      msg: "设置成功",
    };
  } catch (error) {
    throw error;
  }
}

/**
 * 转为正式用户
 */
async function SetFormalUser(Request) {
  try {
    let Body = Request.body;
    let { user } = Body;
    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // 开始更新MYSQL
    let updateUserInfo = await Conline.query(
      `UPDATE users SET ? WHERE id = ${user}`,
      {
        is_user_temporary: 0,
        user_temporary_expire_time: null,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    let affectedRows = updateUserInfo[0].affectedRows;
    if (affectedRows) {
      return {
        code: 0,
        msg: "转换成功",
      };
    } else {
      throw {
        code: 500,
        msg: "转换失败,未知错误",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 转为临时用户
 */
async function SetTemporaryUser(Request) {
  try {
    let Body = Request.body;
    let { user, expire_time } = Body;
    // 当前时间
    let date_now = Request.$requestTime;
    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    }
    if (expire_time) {
      if (date_now > expire_time) {
        throw {
          code: 500,
          msg: "expire_time不能小于当前时间",
        };
      }
    } else {
      expire_time = null;
    }
    // 查询用户信息,是否为超级管理员
    let { data: userInfo } = await GetUserBaseInfo(user);

    let { super_admin } = userInfo;

    if (super_admin) {
      throw {
        code: 500,
        msg: "锁定失败,超级管理员不支持锁定",
      };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // 开始更新MYSQL
    let updateUserInfo = await Conline.query(
      `UPDATE users SET ? WHERE id = ${user}`,
      {
        is_user_temporary: 1,
        user_temporary_expire_time: expire_time,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    let affectedRows = updateUserInfo[0].affectedRows;
    if (affectedRows) {
      return {
        code: 0,
        msg: "转换成功",
      };
    } else {
      throw {
        code: 500,
        msg: "转换失败,未知错误",
      };
    }
  } catch (error) {
    throw error;
  }
}

/**
 * 限制用户登录
 * @param {object} params
 * @param {string} params.user 用户id
 * @param {string} params.duration 限制时长
 * @returns
 */
async function RestrictLogin(params) {
  try {
    let { user, duration } = params;

    if (!user) {
      throw {
        code: 500,
        msg: "用户id不能为空",
      };
    } else if (!duration) {
      throw {
        code: 500,
        msg: "duration不能为空",
      };
    }

    await userExist({ id: user });
    // 限制登录结束时间
    let duration_end_dete = DayJs(Date.now())
      .add(duration, "millisecond")
      .valueOf();
    let updateQuery = `
          UPDATE ${SQLName} SET ? WHERE id = ${user}
      `;
    // 更新用户状态
    await MYSQL.promise().query(updateQuery, {
      restrict_login_state: 1,
      restrict_login_date: duration_end_dete,
    });
    // 删除用户token
    await removeAllToken({ user });

    return {
      code: 0,
      msg: "限制成功",
      duration_end_dete,
    };
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "限制失败" };
  }
}

/**
 * 获取用户token列表
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function UserKeysList(params = {}) {
  try {
    let { user, page } = params;
    if (!user) {
      throw { code: 500, msg: "用户名不能为空" };
    }
    let RedisPath = `${ProjectName}:user:Token:${user}`;
    // 在Redis中查询用户token
    // let RedisUserTokenList = await Redis.
    let limit = 10;
    // 获取Redis列表长度
    let count = await Redis.lLen(RedisPath);
    // 分页Redis查询
    let list = await Redis.lRange(RedisPath, 0, -1);
    // 计算总页数
    let pages = Math.ceil(count / limit);
    return {
      code: 0,
      msg: "操作成功",
      data: {
        page,
        list,
        count,
        pages,
      },
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 清空用户token列表
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function EmptyUserKeysList(Requet) {
  try {
    let Body = Requet.body;
    let { user } = Body;
    if (!user) {
      throw { code: 500, msg: "用户名不能为空" };
    } else {
      let RedisPath = `${ProjectName}:user:Token:${user}`;
      // 清空Reids列表
      await Redis.del(RedisPath);
      return {
        code: 0,
        msg: "操作成功",
      };
    }
  } catch (error) {
    throw error;
  }
}

/**
 * 删除用户token
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function DeleteUserKeys(Request) {}

/**
 * 用户数据纵深
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function userDataObserve() {
  return {
    dayRegisterNumber: null, // 今日注册人数 -
    dayLoginNumber: null, // 今日登录人数 -
    userNumber: null, // 用户总数 -
    maleUserNumber: null, // 男性用户数量 -
    womanUserNumber: null, // 女性用户数量 -
    UnknownGenderUserNumber: null, // 未知性别用户数量 -
    logoffUserNumber: null, // 注销中的用户
    blacklistUserNumber: null, // 黑名单用户数;
  };
}
/**
 * 发布通知
 * @param {object} params
 * @param {string} params.type 通知类型
 * @param {string} params.title 通知标题
 * @param {string} params.value 通知内容
 * @param {string} params.users 通知的用户
 */
async function PublishNotice(Request) {
  try {
    let user = Request.$user;
    let Body = Request.body;
    let { type, title, value, users } = Body;

    // 参数检查
    if (!type) {
      throw {
        code: 500,
        msg: "type不能为空",
      };
    } else if (!title) {
      throw {
        code: 500,
        msg: "title不能为空",
      };
    } else if (!value) {
      throw {
        code: 500,
        msg: "value不能为空",
      };
    }

    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();

    // Sql 语句
    let query = `
            INSERT INTO ${NoticeSqlName} (user,type,title,value) VALUES (${user},${type},${title},${value})
        `;

    let startMysql = await Conline.query(
      `SELECT * FROM ${userSql} WHERE username = ${username}`
    );

    // 查询完毕，释放池连接回池
    await Conline.release();

    // 判断是否发布成功
    if (startMysql[0].affectedRows > 0) {
      return {
        code: 0,
        msg: "发布成功",
      };
    } else {
      throw {
        code: 500,
        msg: "发布失败",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 删除通知
 * @param {object} params
 * @param {string} params.id 通知id
 */
async function DeleteNotice(Request) {
  try {
    let user = Request.$user;

    let Body = Request.body;

    let { id } = Body;

    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // Sql 语句
    let query = `
            DELETE FROM ${NoticeSqlName} WHERE id = ${id}
        `;
    let startMysql = await Conline.query(query);

    // 查询完毕，释放池连接回池
    await Conline.release();

    // 判断是否删除成功
    if (startMysql[0].affectedRows > 0) {
      return {
        code: 0,
        msg: "删除成功",
      };
    } else {
      throw {
        code: 500,
        msg: "删除失败",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 通知列表
 * @param {object} params
 * @param {string} params.page 页码
 */
async function NoticeList(Request) {
  try {
    let query = Request.query;
    let { page, limit } = query;
    let SqlName = "notice"
    return {
      code: 0,
      msg: "获取成功",
    };
  } catch (error) {
    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 通知详细信息
 * @param {object} params
 * @param {string} params.id 通知id
 */
async function NoticeDetail(Request) {
  try {
    let Query = Request.query;
    let { id } = Query;
    if (!id) {
      throw {
        code: 500,
        msg: "id不能为空",
      };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    let query = `
            SELECT * FROM ${NoticeSqlName} WHERE id = ${id}
        `;
    let startMysql = await Conline.query(query);

    // 查询完毕，释放池连接回池
    await Conline.release();

    if (startMysql[0].length > 0) {
      return {
        code: 0,
        msg: "操作成功",
        data: startMysql[0][0],
      };
    } else {
      throw {
        code: 500,
        msg: "操作失败",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 锁定用户
 * @param {object} params
 * @param {string} params.user 用户id
 * @param {string} params.lock_end_date 锁定结束时间
 * @param {string} params.logout 是否注销用户
 * @param {string} params.reason 锁定原因
 */
async function LockUser(Request) {
  try {
    let RequestUser = Request.$user;
    let Body = Request.body;
    let { user, lock_end_date, logout, reason } = Body;
    // 当前时间
    let date_now = Request.$requestTime;
    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    } else if (RequestUser == user) {
      throw {
        code: 500,
        msg: "不能锁定自己！",
      };
    } else if (!lock_end_date) {
      throw {
        code: 500,
        msg: "lock_end_date不能为空",
      };
    } else if (date_now > lock_end_date) {
      throw {
        code: 500,
        msg: "lock_end_date不能小于当前时间",
      };
    }
    // 查询用户信息,是否为超级管理员
    let { data: userInfo } = await GetUserBaseInfo(user);
    let { super_admin } = userInfo;
    if (super_admin) {
      throw {
        code: 500,
        msg: "锁定失败,超级管理员不支持锁定",
      };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // 开始更新MYSQL
    let updateUserInfo = await Conline.query(
      `UPDATE users SET ? WHERE id = ${user}`,
      {
        lock: 1,
        lock_start_date: date_now,
        lock_end_date: lock_end_date,
        lock_reason: reason,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    let affectedRows = updateUserInfo[0].affectedRows;
    if (affectedRows) {
      return {
        code: 0,
        msg: "锁定成功",
      };
    } else {
      throw {
        code: 500,
        msg: "锁定失败,未知错误",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 解除锁定用户
 * @param {object} params
 * @param {string} params.id 通知类型
 */
async function UnlockUser(Request) {
  try {
    let Body = Request.body;

    let { user } = Body;

    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    }

    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();

    // 开始更新MYSQL
    let updateUserInfo = await Conline.query(
      `UPDATE users SET ? WHERE id = ${user}`,
      {
        lock: 0,
        lock_start_date: null,
        lock_end_date: null,
        lock_reason: null,
      }
    );

    // 查询完毕，释放池连接回池
    await Conline.release();

    let affectedRows = updateUserInfo[0].affectedRows;
    if (affectedRows) {
      return {
        code: 0,
        msg: "解除锁定成功",
      };
    } else {
      throw {
        code: 500,
        msg: "锁定失败,未知错误",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 获取账号注销状态
 * @param {object} params
 * @param {string} params.id 通知类型
 */
async function GetUserLogoffStatus(Request) {}
/**
 * 注销列表
 * @param {object} params
 * @param {string} params.id 通知类型
 */
async function LogoffList(Request) {
  try {
    let query = Request.query;

    let { page = 1, limit = 10 } = query;

    limit = limit < 1 ? (limit = 1) : limit;

    page = page < 1 ? (page = 1) : page;

    // 获取MYSQL池链接
    let Conline = await MYSQL.promise().getConnection();
    // 开始查询
    let GetList = await Conline.query(`
            SELECT * FROM users WHERE state = 3 LIMIT  ${limit} OFFSET ${
      (page - 1) * limit
    };
        `);
    // 查询完毕，释放池连接回池
    await Conline.release();
    let List = GetList[0];
    return {
      code: 0,
      msg: "获取成功",
      data: {
        list: List,
        total: List.length,
        page: null,
        pages: null,
      },
    };
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "查询失败" };
  }
}
/**
 * 注销详情
 * @param {object} params
 * @param {string} params.id 通知类型
 */
async function LogoffDetail(Request) {}
/**
 * 同意注销
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AgreeLogoff(Request) {}
/**
 * 拒绝注销
 * @param {object} params
 * @param {string} params.id 通知类型
 */
async function RefuseLogoff(Request) {}
/**
 * 密钥列表
 * @param {object} params
 */
async function GetTokenList(Request) {}
/**
 * 删除密钥
 */
async function DeleteToken(Request) {}
/**
 * 新增密钥
 */
async function AddToken(Request) {}
/**
 * 获取用户行为日志
 */
async function getUserActiveLogList(Request) {}
/**
 * 删除用户行为日志
 */
async function DeleteUserActiveLog(Request) {}
/**
 * 清空用户行为日志
 */
async function EmptyUserActiveLog(Request) {}
/**
 * 用户设备列表
 */
async function GetUserDeviceList(Request) {
  try {
    let query = Request.query;
    let { user, page = 1, limit = 10 } = query;
    limit = limit < 1 ? (limit = 1) : limit;
    page = page < 1 ? (page = 1) : page;
    const Conline = await MYSQL.promise().getConnection();
    // 获取列表数据
    let mysqlResult = await Conline.query(`
		  SELECT * FROM ${deviceSqlName} WHERE user = '${user}'
      LIMIT  ${limit} OFFSET ${(page - 1) * limit};
		`);
    let list = mysqlResult[0];
    // 获取数据总数 =====
    let totalResult = await Conline.query(
      `
       SELECT Count(*) AS total FROM ${deviceSqlName}  WHERE user = ${user}
       
      `
    );
    // 取出数据总数
    let total = totalResult[0][0].total;
    // 根据数据总数计算总页数
    let pages = Math.ceil(total / limit);
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "获取成功",
      data: {
        page,
        pages,
        limit,
        list,
        total,
      },
    };
  } catch (error) {
    console.log(error);

    throw { code: 500, msg: "获取失败" };
  }
}
/**
 * 删除用户设备
 */
async function DeleteUserDevice(Request) {
  try {
    let Body = Request.body;
    let { user, id } = Body;
    const Conline = await MYSQL.promise().getConnection();
    // 获取列表数据
    let mysqlResult = await Conline.query(`
      DELETE FROM ${deviceSqlName} WHERE id = '${id}' AND user = '${user}'
      `);
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "删除成功",
    };
  } catch (error) {
    console.log(error);

    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 清空用户设备
 */
async function EmptyUserDevice(Request) {
  let Body = Request.body;
  let { user } = Body;
  const conn = await MYSQL.promise().getConnection();
  // 获取列表数据
  let mysqlResult = await conn.query(`
		DELETE FROM ${deviceSqlName} WHERE user = '${user}'
		`);
  // 查询完毕，释放池连接回池
  await Conline.release();
  return {
    code: 0,
    msg: "删除成功",
  };
}
/**
 * 设置默认设备
 */
async function SetDefaultDevice(Request) {
  try {
    let Body = Request.body;
    let { user, id } = Body;
    const Conline = await MYSQL.promise().getConnection();
    await Conline.query(`
      	UPDATE ${deviceSqlName} SET
			  if_default = IF(id = ${id}, 1, 0)
			  WHERE user = ${user}
		`);
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "操作成功",
    };
  } catch (error) {
    console.log(error);
    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 获取用户地址列表
 */
async function GetUserAddressList(Request) {
  try {
    let query = Request.query;
    let user = Request.$user;
    let { page = 1, limit = 10 } = query;
    limit = limit ?? limit < 10 ? (limit = 10) : limit;
    page = page ?? page < 1 ? (page = 1) : page;
    const Conline = await MYSQL.promise().getConnection();
    let sqlName = "user_address";
    // 获取列表数据
    let mysqlResult = await Conline.query(`
		SELECT * FROM ${sqlName} WHERE user = '${user}'
    LIMIT  ${limit} OFFSET ${(page - 1) * limit};
    `);
    let list = mysqlResult[0];
    // 获取数据总数 =====
    let totalResult = await Conline.query(
      `
        SELECT Count(*) AS total FROM ${sqlName}  WHERE user = ${user}
      `
    );
    // 取出数据总数
    let total = totalResult[0][0].total;
    // 根据数据总数计算总页数
    let pages = Math.ceil(total / limit);
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "操作成功",
      data: {
        page,
        limit,
        pages,
        total,
        list,
      },
    };
  } catch (error) {
    console.log(error);

    throw { code: 500, msg: "获取失败" };
  }
}
/**
 * 设置用户默认地址
 */
async function SetUserDefaultAddress(Request) {
  try {
    return {
      code: 0,
      msg: "操作成功",
    };
  } catch (error) {
    return {
      code: 500,
      msg: "操作失败",
    };
  }
}

/**
 * 删除用户地址
 */
async function DeleteUserAddress(Request) {
  try {
    let Body = Request.body;
    let { id, user } = Body;
    const Conline = await MYSQL.promise().getConnection();
    await Conline.query(`
      DELETE FROM user_address WHERE id = '${id}' AND user = ${user}
    `);
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "操作成功",
    };
  } catch (error) {
    return {
      code: 500,
      msg: "操作失败",
    };
  }
}

/**
 * 获取用户角色列表
 */
async function GetUserRoleList(Request) {
  return {
    code: 0,
    msg: "操作成功",
  };
}

/**
 * 获取运维数据
 */
async function Observer() {
  try {
    const Conline = await MYSQL.promise().getConnection();
    // 轮播图Redis路径
    let BannerRedisPath = `${ProjectName}:Apply:Banner`;
    let NoticeRedisPath = `${ProjectName}:Apply:Notice`;
    let SystemInfoRedisPath = `${ProjectName}:Apply:SystemInfo`;
    let ManageRedisPath = `${ProjectName}:Apply:Manage`;

    // 短信信息Redis path
    let SmsInfoRedisPath = `${ProjectName}:Apply:SMS:Info`;
    let SmsTotalNumberRedisPath = `${ProjectName}:Apply:SMS:TotalNumber`;
    let SmsToDayNumberRedisPath = `${ProjectName}:Apply:SMS:TodayNumber`;

    // 请求信息
    let RequestInfoRedisPath = `${ProjectName}:Apply:Request:Info`;
    let RequesTotalNumberRedisPath = `${ProjectName}:Apply:Request:TotalNumber`;
    let RequesToDayNumberRedisPath = `${ProjectName}:Apply:Request:TodayNumber`;

    let RequestInfo = await Redis.hgetall(RequestInfoRedisPath);
    let RequesTotalNumber = await Redis.get(RequesTotalNumberRedisPath);
    let RequesTodayNumber = await Redis.get(RequesToDayNumberRedisPath);

    let Request = {
      Attr: {},
      Info: RequestInfo || {},
      TotalNumber: Number(RequesTotalNumber),
      TodayNumber: Number(RequesTodayNumber),
    };

    let SmsInfo = await Redis.hgetall(SmsInfoRedisPath);
    let SmsTotalNumber = await Redis.get(SmsTotalNumberRedisPath);
    let SmsTodayNumber = await Redis.get(SmsToDayNumberRedisPath);

    let SMS = {
      Attr: {},
      Info: SmsInfo || {},
      TotalNumber: Number(SmsTotalNumber),
      TodayNumber: Number(SmsTodayNumber),
    };

    // Banner 数据
    let Banner = {
      current: 0,
      Attr: {
        valueKey: "image",
        current: 0,
        autoplay: true,
        direction: "",
        displayMultipleItems: 1,
        interval: 3000,
        loop: false,
        indicatorPosition: "",
        easingFunction: "",
      },
    };

    let BannerRedis = await Redis.get(BannerRedisPath);
    if (BannerRedis) {
      Banner = JSON.parse(BannerRedis);
    } else {
      let BannerSqlName = "banner";
      let [list] = await Conline.query(`
      SELECT *  FROM ${BannerSqlName}
    `);
      Banner.list = list.map((i) => i.image);
      await Redis.set(BannerRedisPath, JSON.stringify(Banner));
    }
    let Notice = {
      Attr: {},
    };
    let NoticeRedis = await Redis.get(NoticeRedisPath);
    if (NoticeRedis) {
      Notice = JSON.parse(NoticeRedis);
    } else {
      let NoticeSqlName = "notice";
      let [list] = await Conline.query(`
        SELECT *  FROM ${NoticeSqlName}
      `);
      Notice.list = list;
      await Redis.set(NoticeRedisPath, JSON.stringify(Notice));
    }

    let Manage = {
      Attr: {},
    };

    let ManageRedis = await Redis.get(ManageRedisPath);
    if (ManageRedis) {
      Manage = JSON.parse(ManageRedis);
    } else {
      let AppManageGroupSqlName = "app_manage_list_group";
      let [ManageGroupList] = await Conline.query(`
      SELECT *  FROM ${AppManageGroupSqlName}
    `);
      let AppManageListSqLName = "app_manage_list";
      let [ManageArrayList] = await Conline.query(`
      SELECT * FROM  ${AppManageListSqLName}
    `);

      let ManageList = ManageGroupList.map((i) => {
        i.children = ManageArrayList.filter((c) => c.parent == i.id);
        return i;
      });
      let CommonlyList = ManageArrayList.filter((i) => i.commonly);
      Manage.GroupNumber = ManageGroupList.length;
      Manage.ManageListNumber = ManageArrayList.length;
      Manage.list = ManageList;
      Manage.commonly = CommonlyList;
      await Redis.set(ManageRedisPath, JSON.stringify(Manage));
    }
    let optionsList = [
      {
        image:
          "https://img2.baidu.com/it/u=1052523227,3104993244&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800",
        name: "用户管理",
      },
      {
        image:
          "https://img1.baidu.com/it/u=2603829141,3696223612&fm=253&fmt=auto&app=138&f=JPEG?w=473&h=328",
        name: "权限管理",
      },
      {
        image:
          "https://img2.baidu.com/it/u=1052523227,3104993244&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800",
        name: "认证审核",
      },
      {
        image:
          "https://img1.baidu.com/it/u=2603829141,3696223612&fm=253&fmt=auto&app=138&f=JPEG?w=473&h=328",
        name: "通知消息",
      },
      {
        image:
          "https://img2.baidu.com/it/u=1052523227,3104993244&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800",
        name: "用户管理",
      },
      {
        image:
          "https://img1.baidu.com/it/u=2603829141,3696223612&fm=253&fmt=auto&app=138&f=JPEG?w=473&h=328",
        name: "权限管理",
      },
      {
        image:
          "https://img2.baidu.com/it/u=1052523227,3104993244&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800",
        name: "认证审核",
      },
      {
        image:
          "https://img1.baidu.com/it/u=2603829141,3696223612&fm=253&fmt=auto&app=138&f=JPEG?w=473&h=328",
        name: "通知消息",
      },
    ];
    let list = [
      {
        title: "运维数据",
        list: [
          {
            title: "昨日活跃",
            value: null,
            contrast: null,
          },
          {
            title: "今日活跃",
            value: null,
            contrast: null,
          },
          {
            title: "播放量",
            value: null,
            contrast: null,
          },
          {
            title: "播放量",
            value: null,
            contrast: null,
          },
          {
            title: "播放量",
            value: null,
            contrast: null,
          },
          {
            title: "播放量",
            value: null,
            contrast: null,
          },
          {
            title: "播放量",
            value: null,
            contrast: null,
          },
        ],
      },
      {
        title: "短信平台",
        list: [
          {
            title: "总额度",
            value: null,
            contrast: null,
          },
          {
            title: "剩余额度",
            value: null,
            contrast: null,
          },
          {
            title: "已使用",
            value: null,
            contrast: null,
          },
          {
            title: "今日使用",
            value: null,
            contrast: null,
          },
        ],
      },
    ];

    let System = {
      data: {},
      Attr: {
        indicatorDots: true,
        current: 0,
        autoplay: true,
        direction: "",
        displayMultipleItems: 1,
        interval: 3000,
        loop: false,
        indicatorPosition: "",
        easingFunction: "",
      },
    };
    let SystemInfoRedis = await Redis.get(SystemInfoRedisPath);
    System = JSON.parse(SystemInfoRedis);
    // if (SystemInfoRedis) {
    //   System = JSON.parse(SystemInfoRedis)
    // } else {
    //   let SystemInfo = information();
    //   System.data = SystemInfo;
    //   await Redis.set(SystemInfoRedisPath, JSON.stringify(System))
    // }
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "操作成功",
      data: {
        Request,
        SMS,
        Notice,
        Banner,
        optionsList,
        list,
        Manage,
        System,
      },
    };
  } catch (error) {
    console.log("出现错误");
    console.log(error);
    throw {
      code: 500,
      msg: "获取服务器数据台错误",
    };
  }
}

/**
 * 频道列表
 * @return {promise<{code:string,msg:string}>}
 */
async function ChannelList(Request) {
  try {
  } catch (error) {}
}

/**
 * 创建频道
 * @return {promise<{code:string,msg:string}>}
 */
async function CreateChannel(Request) {
  try {
    let Body = Request.body;
    let user = Request.$user;
    let { name, banner } = Body;
    if (!name) {
      throw {
        code: 500,
        msg: "请输入频道名称",
      };
    }
    let Inset = {
      create_user: user,
      name,
      banner: banner || null,
    };
    // 获取Mysql链接
    const Conline = await MYSQL.promise().getConnection();
    let SqlName = "article_channel";
    // 添加Mysql记录
    let [result] = await Conline.query(`INSERT INTO ${SqlName} SET ?`, Inset);
    // 查询完毕，释放池连接回池
    await Conline.release();
    console.log("Result", result);
    return {
      code: 0,
      msg: "操作成功",
    };
  } catch (error) {
    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 删除频道
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteChannel(Request) {
  try {
    let Body = Request.body;
    let { id } = Body;
    // 获取Mysql链接
    const Conline = await MYSQL.promise().getConnection();
    let SqlName = "article_channel";
    // 更新状态为0
    let [affectedRows] = await Conline.query(
      `UPDATE ${SQLName} SET ? WHERE id = ${id}`,
      {
        state: 0,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    if (affectedRows) {
      return {
        code: 0,
        msg: "删除成功",
      };
    } else {
      throw { code: 500, msg: "删除失败,记录不存在" };
    }
  } catch (error) {
    throw {
      code: 500,
      msg: "删除失败",
    };
  }
}
/**
 * 修改频道
 * @return {promise<{code:string,msg:string}>}
 */
async function UpdateChannel(Request) {}
/*
 * 漂流瓶列表
 * @return {promise<{code:string,msg:string}>}
 */
async function GetDriftList(Request) {
  try {
    let user = Request.$user;

    let query = Request.query;

    let {
      page = 1, // 当前页
      limit = 10, // 每页记录数量
    } = query;

    limit = limit < 1 ? (limit = 1) : limit;

    page = page < 1 ? (page = 1) : page;

    const conn = await MYSQL.promise().getConnection();

    let SqlName = "article_drift";

    let MysqlResult = await conn.query(`
      SELECT  *  FROM ${SqlName}
      LIMIT ${(page - 1) * limit + "," + page * limit}
    `);

    let list = MysqlResult[0];

    // 获取数据总数 =====
    let totalResult = await conn.query(
      `
        SELECT Count(*) AS total FROM ${SqlName}
      `
    );
    let total = totalResult[0][0].total;
    let pages = Math.ceil(total / limit);
    await conn.release();
    return {
      code: 0,
      msg: "操作成功",
      data: {
        page,
        pages,
        limit,
        total,
        list,
      },
    };
  } catch (error) {}
}
/*
 * 删除漂流瓶
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteDrift(Request) {
  try {
    let Body = Request.body;
    let { id } = Body;
    // 获取MYSQL实例
    const conn = await MYSQL.promise().getConnection();
    // 删除漂流瓶
    await conn.query(`
      DELETE FROM ${DriftSqlName} WHERE id = ${id}
    `);
    // 释放连接
    await conn.release();
  } catch (error) {}
}
/**
 * 获取用户类型列表
 * @return {promise<{code:string,msg:string}>}
 */
async function GetUserTypeList(Request) {
  try {
    let Query = Request.query;

    let { page, limit } = Query;

    limit = limit < 1 ? (limit = 1) : limit;

    page = page < 1 ? (page = 1) : page;

    const Conline = await MYSQL.promise().getConnection();

    let SqlName = "user_type";

    let MysqlResult = await Conline.query(`
      SELECT *  FROM ${SqlName} 
    `);

    let list = MysqlResult[0];

    // 获取数据总数 =====
    let totalResult = await Conline.query(
      `
       SELECT Count(*) AS total FROM ${SqlName}
      `
    );
    // 取出数据总数
    let total = totalResult[0][0].total;
    // 根据数据总数计算总页数
    let pages = Math.ceil(total / limit);

    // 查询完毕，释放池连接回池
    await Conline.release();

    return {
      code: 0,
      msg: "操作成功",
      data: {
        page,
        limit,
        list,
        total,
        pages,
      },
    };
  } catch (error) {
    throw error;
  }
}

/**
 * 修改用户类型
 * @return {promise<{code:string,msg:string}>}
 */
async function UpdateUserType(Request) {}

/**
 * 删除用户类型
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteUserType(Request) {
  try {
    let Body = Request.body;

    let { id } = Body;

    const Conline = await MYSQL.promise().getConnection();

    let SqlName = "user_type";

    await Conline.query(
      `
       DELETE FROM ${SqlName} WHERE id = '${id}'
      `
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "删除成功",
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 创建用户类型
 * @return {promise<{code:string,msg:string}>}
 */
async function CreateUserType(Request) {
  try {
    let Body = Request.body;

    let { id } = Body;

    const Conline = await MYSQL.promise().getConnection();

    let SqlName = "user_type";

    await Conline.query(
      `
       DELETE FROM ${SqlName} WHERE id = '${id}'
      `
    );
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "删除成功",
    };
  } catch (error) {
    throw error;
  }
}

// 将所有函数暴露出去
module.exports = {
  ChannelList,
  UpdateChannel,
  DeleteChannel,
  CreateChannel,

  UpdateUserType,
  CreateUserType,
  DeleteUserType,
  GetUserTypeList,

  Observer,
  GetUserRoleList,
  GetUserAddressList,
  SetUserDefaultAddress,
  DeleteUserAddress,
  ToBlack,
  Blacklist,
  CancelBlack,
  UserKeysList,
  EmptyUserKeysList,
  DeleteUserKeys,
  userDataObserve,

  PublishNotice,
  DeleteNotice,
  NoticeList,
  NoticeDetail,

  LogoffList,
  LogoffDetail,
  AgreeLogoff,
  RefuseLogoff,

  userList,
  GetUserBaseInfo,
  GetUserRealInfo,
  UpdateUserBaseInfo,
  UpdateUserRealInfo,
  UserRealList,
  ResetReal,
  RefuseReal,
  PassReal,
  ProhibitReal,
  CancelProhibitReal,
  DeleteUser,
  SetSuperUser,
  getUserActiveLogList,
  GetUserDeviceList,
  LockUser,
  UnlockUser,

  EmptyUserDevice,
  DeleteUserDevice,
  SetDefaultDevice,
  GetDriftList,

  ResetUserPassword,
};
